package nconv.wiki;

import nconv.convert.ConvertContext;
import nconv.utils.LogCenter;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by xiaobyu on 4/5/2016.
 */
public class WikiPageMigrator {

    static final String PAGE_NAME_AVP_CATEGORY = "Category:AVP";
    static final String PAGE_NAME_TEMPLATES = "Special:Templates";

    static boolean migrateAVPs = true;
    static boolean migrateTemplates = false;

    static MediaWikiProxy specWiki;

    static {
        specWiki = new MediaWikiProxy("http://10.113.4.62:5800/mediawiki", "Lambert Yu", "pqmj3w");
        MediaWikiProxy.registerWikiSite(MediaWikiProxy.WikiSite.SPEC_WIKI,  specWiki);
    }

    public static void main(String[] args) throws Exception{

        SSLUtilities.trustAllHostnames();
        SSLUtilities.trustAllHttpsCertificates();
        ConvertContext.setDocType(ConvertContext.DOC_TYPE.SYNC);
        MediaWikiProxy autoWiki = MediaWikiProxy.getWikiSite(MediaWikiProxy.WikiSite.AUTO_WIKI);
        URL url = null;
        String body = null;

        int count = 0;
        if (migrateTemplates) {
            //continue with template migration
            url = new URL("https://10.113.4.62/wiki/" + PAGE_NAME_TEMPLATES);
            body = fetchURL(url, null);

            Pattern pattern = Pattern.compile("<a href=\"/wiki/Template:.+\" title=\"(Template:(.+))\">\\2</a>");
            Pattern next50Templates = Pattern.compile("<a href=\"([^\\s]+)\" title=\"Next 50 results\"");
            while (true) {
                Matcher m = pattern.matcher(body);
                while (m.find()) {
                    String target = m.group(1);
                    if (target.contains("Impl:")) {
                        LogCenter.log("Skipped a template page: " + target);
                        continue;
                    }
                    String content = specWiki.getPageContent(target);
                    if (content != null) {
                        autoWiki.createPage(target, content, "Edit template page");
                        LogCenter.log("Processed template #" + ++count + ": " + target);
                    }
                }
                m = next50Templates.matcher(body);
                if (m.find()) {
                    body = fetchURL(url, m.group(1).replaceAll("&amp;", "&"));
                } else {
                    break;
                }
            }
        }

        if (migrateAVPs) {
            count = 0;
            url = new URL("https://10.113.4.62/wiki/Category:AVP");
            body = fetchURL(url, null);
            Pattern pattern = Pattern.compile("<a href=\"/wiki/([^\\s]+)\" ");

            String catPage = specWiki.getPageContent(PAGE_NAME_AVP_CATEGORY);
            if (catPage != null) {
                autoWiki.createPage(PAGE_NAME_AVP_CATEGORY, catPage, "AVP category page");
            }
            Pattern next200AVP = Pattern.compile("<a href=\"([^\\s]+)\" title=\"Category:AVP\">next 200</a>");
            while (true) {
                Matcher m = pattern.matcher(body);
                while (m.find()) {
                    String target = m.group(1);
                    if (target.indexOf(':') < 0) {
                        String content = specWiki.getPageContent("AVP:" + target);
                        if (content != null) {
                            content = "{{Ambox\n" +
                                    "|nocat=true\n" +
                                    "| type  = content\n" +
                                    "| text  = This page was migrated automatically from specwiki site, any changes please commit to " +
                                    "the AVP page [https://10.113.4.62/wiki/AVP:" + target + " AVP:" + target +
                                    "] at [https://10.113.4.62/wiki specwiki].\n" +
                                    "}}\n" + content;
                            autoWiki.createPage("AVP:" + target, content, "Edit AVP page");
                            String rawAVPPageContent = "#REDIRECT [[AVP:" + target + "]]\n\n" + "[[Category:AVP]]";
                            autoWiki.createPage(target, rawAVPPageContent, "Edit AVP source page");
                            LogCenter.log("Processed AVP #" + ++count + ": " + target);
                        }
                    }
                }
                m = next200AVP.matcher(body);
                if (m.find()) {
                    body = fetchURL(url, m.group(1).replaceAll("&amp;", "&"));
                } else {
                    break;
                }
            }
        }

        LogCenter.updateLogs();
    }

    private static String fetchURL(URL base, String urlStr) throws IOException {
        URL url = null;
        if (base == null) {
            url = new URL(urlStr);
        } else if (urlStr == null) {
            url = base;
        } else {
            url = new URL(base, urlStr);
        }
        System.out.println(url);
        URLConnection con = url.openConnection();
        InputStream in = con.getInputStream();
        String encoding = con.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        return IOUtils.toString(in, encoding);
    }
}
